﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.Mvc;
using System.Web.Routing;
using ShopB2C.Entity;
using ShopB2C.Enums;
using ShopB2C.Helper;
using ShopB2C.Interfaces;
using ShopB2C.Parameters;
using ShopB2C.ViewModels;

namespace ShopB2C.Controllers.Brower {
    public partial class CommentController : BaseController {
        private static IProductPreview _productPreView;
        private static IClassify _classify;
        private static IComment _comment;
        private static string _userFaceRoot;
        private const string _moduleKey = "Product";

        public CommentController() {
            _productPreView = DataBaseExecuter.CreateClassByName<IProductPreview>("ProductPreView");
            _classify = DataBaseExecuter.CreateClassByName<IClassify>("ClassIfy");
            _comment = DataBaseExecuter.CreateClassByName<IComment>("Comment");
            _userFaceRoot = ConfigHelper.GetValue(ConfigNodeNames.System, "UserFaceRoot");
        }

        protected override void Initialize(RequestContext requestContext) {
            base.Initialize(requestContext);
            this.SiteMapPathAdd("首页", Url.Action("Index", "Home"));
            this.SiteMapPathAdd("所有商品", Url.Action("ProductList", "Product", new {
                productParams = new ProductParam().ToString()
            }));
            ViewData["ImageRoot"] = _imageRoot;
        }

        // 评论
        public ActionResult CommentList([DefaultValue("0-1-1-0")]string commentParams) {
            CommentParam cp = Methods.FormatCommentParams(commentParams);
            ProductEntity productView = _productPreView.ProductView(cp.ProductId, _user.Uid);
            if (productView == null) {
                return Content("没有找到相关商品信息!");
            }
            // 评论
            CommentParameters cpa = new CommentParameters() {
                ProductId = cp.ProductId,
                SortField = cp.SortFieldName,
                GradeValue = cp.GradeValue,
                PageIndex = cp.PageIndex,
                PageSize = 10,
                Uid = this._user.Uid
            };
            List<CommentEntity> commentList = _comment.GetCommentList(cpa);
            // 评论回复
            List<CommentEntity> reCommentList = _comment.GetCommentList(new CommentParameters() {
                ProductId = cp.ProductId,
                IsReply = CommentType.Reply,
                Uid = this._user.Uid
            });
            // 评分
            List<CommentCount> countList = _comment.GetCommentCount(cp.ProductId);
            this.AddSiteMapPath(productView);
            this.SiteMapPathAdd(productView.SubName,
                Url.Action("PreView", "Product", new { ProductId = cp.ProductId }));
            this.SiteMapPathAdd("商品评论");
            // 分页
            CommentParam cpPager = cp.Clone();
            cpPager.PageIndex = 1234554321;
            object pager = this.CreatePager(Url.Action("CommentList", "Comment", new {
                commentParams = cpPager.ToString().Replace("1234554321", "{0}")
            }), cpa.PageCount, cp.PageIndex);
            // url
            Dictionary<CommentSortFieldNames, string> sortDict =
                new Dictionary<CommentSortFieldNames, string>();
            foreach (int i in Enum.GetValues(typeof(CommentSortFieldNames))) {
                CommentParam cpX = cp.Clone();
                cpX.SortFieldName = (CommentSortFieldNames)i;
                cpX.PageIndex = 1;
                sortDict.Add(cpX.SortFieldName,
                    Url.Action("CommentList", new { commentParams = cpX.ToString() }));
            }

            Dictionary<CommentGradeValues, string> searchDict =
                new Dictionary<CommentGradeValues, string>();
            foreach (int i in Enum.GetValues(typeof(CommentGradeValues))) {
                CommentParam cpX = cp.Clone();
                cpX.GradeValue = (CommentGradeValues)i;
                cpX.PageIndex = 1;
                searchDict.Add(cpX.GradeValue,
                    Url.Action("CommentList", new { commentParams = cpX.ToString() }));
            }

            return View(new CommentViewModel() {
                ImageRoot = _imageRoot,
                UserFaceRoot = _userFaceRoot,
                Product = productView,
                CommentList = commentList ?? new List<CommentEntity>(),
                ReCommentList = reCommentList ?? new List<CommentEntity>(),
                CommentCountList = countList,
                CommentParams = cp,
                RowsCount = cpa.RowsCount,
                Pager = pager,
                SortDict = sortDict,
                SearchDict = searchDict
            });
        }
        // 删除
        public ActionResult CommentDelete(
            [DefaultValue(0)]int productId,
            [DefaultValue(0)]int commentId,
            [DefaultValue(0)]int reCommentId) {

            _comment.CommentDelete(commentId.ToString());
            return RedirectToAction("CommentList",
                new { commentParams = string.Format("{0}-1-1-0", productId) });
        }
        // 发表
        [Authorize()]
        public ActionResult CommentEdit(
            [DefaultValue(0)]int productId,
            [DefaultValue(0)] int commentId,
            [DefaultValue(0)] int reCommentId) {

            ProductEntity productView = _productPreView.ProductView(productId, _user.Uid);
            this.AddSiteMapPath(productView);
            this.SiteMapPathAdd(productView.SubName,
                Url.Action("PreView", "Product", new { ProductId = productId }));
            this.SiteMapPathAdd("发表评论");

            CommentEntity ce = new CommentEntity();

            #region 检查数据合法性

            MessageHelper mh = new MessageHelper("comment");
            mh.AddBody(1);
            if (productId < 1) {
                mh.AddMessage(1);
            }
            if (commentId > 0) {
                ce = _comment.GetCommentById(commentId);
                if (ce == null) {
                    mh.AddMessage(5);
                }
                else {
                    if (ce.Uid != this._user.Uid) {
                        mh.AddMessage(8);
                    }
                    else if (ce.ReplyNum > 0) {
                        mh.AddMessage(6);
                    }
                }
            }
            else {
                ce.ReCommentId = reCommentId;
                if (reCommentId < 0) {
                    mh.AddMessage(2);
                }
                else if (reCommentId > 0) {
                    CommentEntity reCe = _comment.GetCommentById(reCommentId);
                    if (reCe == null) {
                        mh.AddMessage(2);
                    }
                    else {
                        if (!reCe.IsAudit) {
                            mh.AddMessage(7);
                        }
                    }
                }
            }
            if (!mh.IsValid) {
                return this.MessageResult(mh.CreateMessage());
            }

            #endregion

            ce.Content = Htmls.DecodeHtml(ce.Content);
            return View(new CommentViewModel() {
                Comment = ce,
                Product = _productPreView.ProductView(productId, this._user.Uid)
            });
        }
        [Authorize(), HttpPost]
        public ActionResult CommentEdit(CommentViewModel cvm) {

            #region 检查数据合法性

            MessageHelper mh = new MessageHelper("comment");
            mh.AddBody(2);
            if (cvm.Comment.GradeValue < 1) {
                mh.AddMessage(3);
            }
            if (string.IsNullOrEmpty(cvm.Comment.Content)) {
                mh.AddMessage(4);
            }
            if (!mh.IsValid) {
                return this.MessageResult(mh.CreateMessage());
            }

            #endregion

            cvm.Comment.Content = Htmls.EncodeHtml(cvm.Comment.Content);
            cvm.Comment.ProductId = cvm.Product.ProductId;
            cvm.Comment.Uid = this._user.Uid;
            cvm.Comment.GradeValue =
                cvm.Comment.CommentId == 0 && cvm.Comment.ReCommentId > 0 ? 0 : cvm.Comment.GradeValue;

            _comment.CommentUpdate(cvm.Comment);

            return RedirectToAction("CommentList",
                new { commentParams = string.Format("{0}-1-1-0", cvm.Product.ProductId) });
        }

        #region AJAX

        [HttpPost]
        public ActionResult AjaxList([DefaultValue(0)]int productId) {
            List<CommentEntity> commentList = _comment.GetCommentList(new CommentParameters() {
                ProductId = productId,
                PageIndex = 1,
                PageSize = 5,
                GradeValue = CommentGradeValues.All,
                IsReply = CommentType.Comment,
                SortField = CommentSortFieldNames.Newest,
                Uid = this._user.Uid
            });
            List<CommentEntity> reCommentList = _comment.GetCommentList(new CommentParameters() {
                ProductId = productId,
                IsReply = CommentType.Reply
            });
            List<CommentCount> countList = _comment.GetCommentCount(productId);

            return View(new CommentViewModel() {
                CommentList = commentList ?? new List<CommentEntity>(),
                ReCommentList = reCommentList ?? new List<CommentEntity>(),
                CommentCountList = countList,
                UserFaceRoot = _userFaceRoot,
                CommentParams = new CommentParam() { ProductId = productId, GradeValue = 0 }
            });
        }

        #endregion

        #region Private Methods

        private void AddSiteMapPath(ProductEntity productView) {
            // 当前分类
            ClassifyEntity currentClass = _classify.GetClassifyById(productView.ClassId);
            // sitemappath
            List<ClassifyEntity> pathList =
                _classify.GetClassifyByModuleKeyAndPath(_moduleKey,
                string.Format("{0}-{1}", currentClass.Path, currentClass.ClassifyId));
            if (pathList != null) {
                List<int> cPathList = new List<int>() { 0 };
                foreach (ClassifyEntity ce in pathList) {
                    cPathList.Add(ce.ClassifyId);
                    ProductParam ppPath = new ProductParam() {
                        Classify = cPathList
                    };
                    this.SiteMapPathAdd(ce.Title.Trim(), Url.Action("ProductList", "Product", new {
                        productParams = ppPath.ToString()
                    }));
                }
            }
        }

        #endregion
    }
}
